package com.piece.core.mongo.context;

import com.piece.core.framework.support.bootstrap.QueryTable;
import com.piece.core.framework.util.math.SequenceUtil;
import com.piece.core.framework.util.object.BeanUtil;
import com.piece.core.log.client.MessageLogService;
import com.piece.core.log.client.dto.MessageLogDTO;
import com.piece.core.mongo.entity.MongoMessageLog;
import com.piece.core.mongo.service.MongoMessageLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component("message_log_service_mongo")
@ConditionalOnProperty(name = "spring.log.type", havingValue = "mongo")
public class MessageLogServiceMongoImpl implements MessageLogService {

    @Resource
    private MongoMessageLogService mongoMessageLogService;

    @Override
    public MessageLogDTO save(MessageLogDTO logDTO) {
        MongoMessageLog messageLog = convertToDb(logDTO);
        messageLog.setLogId(SequenceUtil.uuid());
        messageLog = mongoMessageLogService.insert(messageLog);
        logDTO.setLogId(messageLog.getLogId());
        return logDTO;
    }

    @Override
    public void delete(MessageLogDTO logDTO) {
        mongoMessageLogService.delete(logDTO.getLogId());
    }

    @Override
    public void clear() {
        mongoMessageLogService.deleteAll(null);
    }

    @Override
    public List<MessageLogDTO> findByCondition(Map<String, Object> param) {
        QueryTable queryTable = new QueryTable();
        queryTable.setParams(param);
        List<MongoMessageLog> logs = mongoMessageLogService.findList(queryTable);
        return logs.stream().map(messageLog -> {
            MessageLogDTO logDTO = null;
            try {
                logDTO = convertToLog(messageLog);
            } catch (Exception e) {
                log.error("转换日志对象异常：{}", e.getMessage());
            } finally {
                return logDTO;
            }
        }).collect(Collectors.toList());
    }

    private MongoMessageLog convertToDb(MessageLogDTO logDTO) {
        MongoMessageLog messageLog = new MongoMessageLog();
        BeanUtil.copyProperties(logDTO, messageLog);
        return messageLog;
    }

    private MessageLogDTO convertToLog(MongoMessageLog messageLog) {
        MessageLogDTO logDTO = new MessageLogDTO();
        BeanUtil.copyProperties(messageLog, logDTO);
        return logDTO;
    }
}
